import { PageLoading } from '@ant-design/pro-layout';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import { requestInterceptors, responseInterceptors, errorHandler } from '@/utils/Request';
import { getCurrentUserMenus } from './services/ant-design-pro/menu';
import fixMenuItemIcon from '@/utils/fixMenuItemIcon';
import SwitchTabsLayout from './layouts/SwitchTabsLayout';
import defaultSettings from '../config/defaultSettings';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
/** 获取用户信息比较慢的时候会展示一个 loading */

export const initialStateConfig = {
  loading: <PageLoading />,
};
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

 export async function getInitialState() {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      const currentUser={...msg.user,permissions: msg.permissions};
      console.log("login user info:",currentUser);
      return currentUser;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  if (history.location.pathname !== loginPath) {
    const token = localStorage.getItem('access_token');
    if (!token) {
      history.push(loginPath);
      return {
        fetchUserInfo,
        currentUser:{},
        settings: defaultSettings,
      };
    }
    const currentUser = await fetchUserInfo();

    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }

  return {
    fetchUserInfo,
    currentUser,
    settings: defaultSettings,
  };
}
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const request = {
  errorHandler,
  requestInterceptors: [requestInterceptors],
  responseInterceptors: [responseInterceptors],
};
export const layout = ({ initialState,setInitialState  }) => {
  const { switchTabs, ...restSettings } = initialState?.settings || {};

  return {
  rightContentRender: () => (
      <RightContent switchTabsReloadable={switchTabs?.mode && switchTabs.reloadable} />
    ),
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    className: switchTabs?.mode && 'custom-by-switch-tabs',
    childrenRender: (children, props) => {
      const { route } = props;
      return (
        <SwitchTabsLayout
          mode={switchTabs?.mode}
          persistent={switchTabs?.persistent}
          fixed={switchTabs?.fixed}
          routes={route.routes}
          footerRender={() => <Footer />}
        >
          {children}
        </SwitchTabsLayout>
      );
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history; // 如果没有登录，重定向到 login

      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
          <Link to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    menu: {
      // 每当 initialState?.currentUser?.userId 发生修改时重新执行 request
      params: {
        userId: initialState?.currentUser?.userId,
      },
      request: async (params, defaultMenuData) => {

        const tempMenuData = await getCurrentUserMenus();
        const menuData=fixMenuItemIcon(tempMenuData);
        setInitialState({
          ...initialState,
          menuData: menuData,
        });
        return menuData;
      },
    },

    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...restSettings,
  };
};
